package com.example.usermanagement.controller;

import com.example.usermanagement.dto.JwtResponse;
import com.example.usermanagement.dto.LoginDTO;
import com.example.usermanagement.dto.UserDTO;
import com.example.usermanagement.service.AuthService;
import com.example.usermanagement.service.UserService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    private final AuthService authService;
    private final UserService userService;

    public AuthController(AuthService authService, UserService userService) {
        this.authService = authService;
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginDTO loginDTO) {
        logger.info("收到登录请求: username={}", loginDTO.getUsername());
        System.out.println("收到登录请求: username=" + loginDTO.getUsername() + ", password=" + loginDTO.getPassword());
        try {
            JwtResponse response = authService.authenticateUser(loginDTO);
            logger.info("登录成功: username={}", loginDTO.getUsername());
            System.out.println("登录成功: username=" + loginDTO.getUsername());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("登录失败: username={}, error={}", loginDTO.getUsername(), e.getMessage(), e);
            System.out.println("登录失败: username=" + loginDTO.getUsername() + ", error=" + e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body("登录失败: " + e.getMessage());
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody UserDTO userDTO) {
        logger.info("收到注册请求: username={}", userDTO.getUsername());
        System.out.println("收到注册请求: username=" + userDTO.getUsername() + ", email=" + userDTO.getEmail());
        try {
            userService.registerUser(userDTO);
            logger.info("注册成功: username={}", userDTO.getUsername());
            System.out.println("注册成功: username=" + userDTO.getUsername());
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body("注册成功");
        } catch (Exception e) {
            logger.error("注册失败: username={}, error={}", userDTO.getUsername(), e.getMessage(), e);
            System.out.println("注册失败: username=" + userDTO.getUsername() + ", error=" + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("注册失败: " + e.getMessage());
        }
    }
}